import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { Game } from './components/Game';
import { Debug } from './utils/Debug';
import './style.css';

// 是否启用调试模式
const DEBUG_MODE = true; // 临时开启调试模式
// 是否显示性能监控
const SHOW_PERFORMANCE = true; // 临时开启性能监控

// 初始化调试工具
Debug.init(DEBUG_MODE);
Debug.captureErrors();

let game: Game | null = null;

// 加载屏幕元素
const loadingElement = document.getElementById('loading') as HTMLDivElement;
const progressBar = document.getElementById('progress-bar') as HTMLDivElement;
const startButton = document.getElementById('start-button') as HTMLButtonElement;
const loadingText = document.getElementById('loading-text') as HTMLDivElement || document.createElement('div');

// 如果加载文本元素不存在，创建一个
if (!document.getElementById('loading-text')) {
  loadingText.id = 'loading-text';
  loadingText.style.position = 'absolute';
  loadingText.style.bottom = '10px';
  loadingText.style.width = '100%';
  loadingText.style.textAlign = 'center';
  loadingText.style.color = '#fff';
  loadingElement.appendChild(loadingText);
}

// 游戏界面元素
const scoreElement = document.getElementById('score') as HTMLDivElement;
const healthElement = document.getElementById('health') as HTMLDivElement;
const gameOverElement = document.getElementById('game-over') as HTMLDivElement;
const finalScoreElement = document.getElementById('final-score') as HTMLDivElement;
const restartButton = document.getElementById('restart-button') as HTMLButtonElement;

// 添加控制说明
const controlsInfo = document.createElement('div');
controlsInfo.id = 'controls-info';
controlsInfo.style.position = 'fixed';
controlsInfo.style.bottom = '20px';
controlsInfo.style.left = '20px';
controlsInfo.style.color = 'white';
controlsInfo.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
controlsInfo.style.padding = '10px';
controlsInfo.style.borderRadius = '5px';
controlsInfo.style.fontSize = '14px';
controlsInfo.style.zIndex = '100';
controlsInfo.innerHTML = `
  <h3>控制说明:</h3>
  <p>WASD: 移动坦克</p>
  <p>鼠标: 控制炮塔方向</p>
  <p>鼠标左键/空格键: 射击</p>
  <p>F1: 切换调试模式</p>
  <p>F2: 切换性能监控</p>
`;
document.body.appendChild(controlsInfo);

// 资源加载管理器
const loadingManager = new THREE.LoadingManager();

// 设置加载超时
const LOADING_TIMEOUT = 20000; // 20秒
let loadingTimeout: number;

// 重置加载超时
function resetLoadingTimeout() {
  if (loadingTimeout) {
    clearTimeout(loadingTimeout);
  }
  
  loadingTimeout = setTimeout(() => {
    Debug.warn('资源加载超时，强制开始游戏');
    forceStartGame();
  }, LOADING_TIMEOUT);
}

// 强制开始游戏
function forceStartGame() {
  progressBar.style.width = '100%';
  startButton.style.display = 'block';
  loadingText.textContent = '加载完成（部分资源可能缺失）';
}

// 监听加载进度
loadingManager.onProgress = (url, loaded, total) => {
  resetLoadingTimeout();
  
  const progress = (loaded / total) * 100;
  progressBar.style.width = `${progress}%`;
  loadingText.textContent = `加载中...${Math.round(progress)}%（${loaded}/${total}）- ${url.split('/').pop()}`;
  
  Debug.log(`加载进度: ${Math.round(progress)}%（${loaded}/${total}）- ${url}`);
};

// 加载完成后显示开始按钮
loadingManager.onLoad = () => {
  if (loadingTimeout) {
    clearTimeout(loadingTimeout);
  }
  
  Debug.log('所有资源加载完成');
  progressBar.style.width = '100%';
  startButton.style.display = 'block';
  loadingText.textContent = '加载完成，点击开始游戏！';
  
  // 预先创建游戏实例但不启动
  createGameInstance();
};

// 加载出错处理
loadingManager.onError = (url) => {
  Debug.error(`资源加载错误: ${url}`);
  loadingText.textContent = `资源加载错误: ${url.split('/').pop()}`;
  
  // 如果有错误，等待3秒后强制继续
  setTimeout(() => {
    progressBar.style.width = '100%';
    startButton.style.display = 'block';
    loadingText.textContent = '部分资源加载失败，但您仍可以开始游戏';
  }, 3000);
};

// 创建游戏实例但不启动
function createGameInstance() {
  Debug.log('创建游戏实例');
  try {
    game = new Game(
      loadingManager, 
      {
        onScoreChange: (score: number) => {
          scoreElement.textContent = `分数: ${score}`;
        },
        onHealthChange: (health: number) => {
          healthElement.textContent = `生命值: ${health}`;
        },
        onGameOver: (finalScore: number) => {
          finalScoreElement.textContent = `最终分数: ${finalScore}`;
          gameOverElement.style.display = 'flex';
        }
      },
      {
        debug: DEBUG_MODE,
        showPerformance: SHOW_PERFORMANCE
      }
    );
    Debug.log('游戏实例创建成功');
  } catch (error) {
    Debug.error(`创建游戏实例时出错: ${error}`);
    loadingText.textContent = '创建游戏实例时出错，请刷新页面重试';
  }
}

// 初始化游戏
function startGame() {
  Debug.log('开始游戏');
  
  // 显示控制说明
  controlsInfo.style.display = 'block';
  
  // 5秒后隐藏控制说明
  setTimeout(() => {
    controlsInfo.style.opacity = '0.3';
  }, 5000);
  
  // 如果游戏实例未创建，则创建它
  if (!game) {
    createGameInstance();
  }
  
  try {
    // 开始游戏循环
    game?.start();

    // 处理窗口大小改变
    window.addEventListener('resize', () => {
      game?.resize(window.innerWidth, window.innerHeight);
    });
    
    Debug.log('游戏成功启动');
  } catch (error) {
    Debug.error(`启动游戏时出错: ${error}`);
    alert('启动游戏时出错，请刷新页面重试');
  }
}

// 开始游戏按钮事件监听
startButton.addEventListener('click', () => {
  loadingElement.style.opacity = '0';
  setTimeout(() => {
    loadingElement.style.display = 'none';
    startGame();
  }, 500);
});

// 重新开始游戏按钮事件监听
restartButton.addEventListener('click', () => {
  gameOverElement.style.display = 'none';
  game?.restart();
});

// 键盘快捷键
document.addEventListener('keydown', (event) => {
  if (event.key === ' ' && loadingElement.style.display !== 'none') {
    Debug.log('使用空格键应急启动游戏');
    event.preventDefault();
    loadingElement.style.opacity = '0';
    setTimeout(() => {
      loadingElement.style.display = 'none';
      startGame();
    }, 500);
    return;
  }
  
  if (event.key === ' ' && game && loadingElement.style.display === 'none') {
    Debug.log('使用空格键射击');
  }
  
  if (game) {
    switch(event.key) {
      case 'F1':
        event.preventDefault();
        game.toggleDebugMode();
        Debug.log('调试模式已切换');
        break;
      case 'F2':
        event.preventDefault();
        game.togglePerformanceMonitor();
        Debug.log('性能监控已切换');
        break;
      case 'F3':
        event.preventDefault();
        Debug.setEnabled(!Debug.isEnabled());
        Debug.log('调试显示已切换');
        break;
      case 'F4':
        event.preventDefault();
        controlsInfo.style.display = controlsInfo.style.display === 'none' ? 'block' : 'none';
        Debug.log('控制说明显示已切换');
        break;
      case 'F5':
        event.preventDefault();
        location.reload();
        break;
    }
  }
});

// 初始化加载超时
resetLoadingTimeout();

// 确保页面加载完毕后执行
document.addEventListener('DOMContentLoaded', () => {
  Debug.log('DOM加载完成，准备开始加载游戏资源');
}); 